# 获取小程序的access_token,这个与小程序绑定
import os
import threading
from tkinter import EXCEPTION
import requests
import json
from app.static import WX_GET_ACCESS_TOKEN_URL, WX_ACCESS_TOKEN
from django.core.cache import cache
from app.static import AccessKeyID, AccessKeySecret, ENDPOINT, BUCKET
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
import random
import oss2
from pymysql import Connect
from dbutils.pooled_db import PooledDB


class HttpSuccess:
    def __init__(self, data:object ="", msg=""):
        if isinstance(data,object) and hasattr(data,"__dict__"):
            data = vars(data)
        self.code = 200
        self.data = data
        self.msg = msg

    def setMsg(self, msg=""):
        self.msg = msg

    def setData(self, data):
        if isinstance(data,object):
            data = vars(data)
        self.data = data


class HttpError(Exception):
    def __init__(self, code=500, msg=""):
        super().__init__()
        self.code = code
        self.msg = msg

    def setMsg(self, msg=""):
        self.msg = msg


class HttpPage:
    def __init__(self, list, totalPage):
        self.list = list
        self.totalPage = totalPage

    def setList(self, list):
        self.list = list

    def setTotalPage(self, totalPage):
        self.totalPage = totalPage

    def __str__(self):
        return self.__dict__


def getWxAccessToken(appid, secret):
    wxaccesstoken = cache.get(WX_ACCESS_TOKEN)
    if wxaccesstoken:
        return wxaccesstoken
    else:
        params = {"appid": appid, "secret": secret, "grant_type": "client_credential"}
        res = requests.get(WX_GET_ACCESS_TOKEN_URL, params)
        resText = json.loads(res.text)
        cache.set(WX_ACCESS_TOKEN, resText["access_token"], 7200)
        return resText["access_token"]


def upload(file_obj):
    # BUCKET_ACL_TYPE = oss2.OBJECT_ACL_PUBLIC_READ

    # 初始化OSS
    auth = oss2.Auth(AccessKeyID, AccessKeySecret)
    bucket = oss2.Bucket(auth, ENDPOINT, BUCKET)

    # 文件名使用原始文件名，你也可以自定义
    file_name = file_obj.name
    # 上传文件
    result = bucket.put_object(file_name, file_obj.file)
    url = "https://" + BUCKET + "." + ENDPOINT + "/" + file_name
    return url


class message_cli:
    def __init__(self):
        pass

    def create_client(self):
        config = open_api_models.Config(
            access_key_id=AccessKeyID, access_key_secret=AccessKeySecret
        )
        config.endpoint = f"dysmsapi.aliyuncs.com"
        self.dysmsapi20170525Client = Dysmsapi20170525Client(config)

    def send_message(self, number, code):
        ##判断有没有发送过
        if cache.get(number):
            return "验证码3分钟内有效，请勿重复获取"
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name="阿里云短信测试",
            template_code="SMS_154950909",
            phone_numbers=number,
            template_param=json.dumps({"code": code}),
        )
        runtime = util_models.RuntimeOptions()
        try:
            self.dysmsapi20170525Client.send_sms_with_options(send_sms_request, runtime)
            ##发送成功存在redis，时间周期为3分钟
            cache.set(number, code, 3 * 60)
            return "发送成功"
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            return error.message


# class DBUtils_class:
#     def __new__(cls, *args, **kwargs):
#         if not hasattr(DBUtils_class, "_instance"):
#             DBUtils_class._instance = object.__new__(cls, *args, **kwargs)
#         return DBUtils_class._instance
#     def __init__(self):
#         self.pool = PooledDB(
#             creator=Connect,
#             host="localhost",
#             user="root",
#             password="123456",
#             database="xinyu",
#             mincached=2,
#             maxcached=5,
#             maxshared=3,
#             blocking=True,
#             maxconnections=10,
#         )

#     def get_connection(self):
#         conn = self.pool.connection()
#         cur = conn.cursor()
#         return cur, conn

#     def execute_select(self, sql):
#         cur, conn = self.pool.get_connection()
#         try:
#             cur.execute(sql)
#             return True, cur.fetchall()
#         except BaseException as e:
#             print(e)
#             return False, None
#         finally:
#             cur.close()
#             conn.close()


# DBUtils = DBUtils_class()
# class DBUtils(object):
#     pool = None
#     @staticmethod
#     def init():
#         print(DBUtils.pool)
#         if DBUtils.pool == None:
#             DBUtils.pool = PooledDB(
#                 creator=Connect,  # 使用链接数据库的模块
#                 host="localhost",
#                 user="root",
#                 password="123456",
#                 database="xinyu",
#                 mincached=2,
#                 maxcached=5,
#                 maxshared=3,
#                 blocking=True,
#                 maxconnections=10,
#             )
    

# DBUtils.init()
